package com.yicong.ants.service;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;

import com.yicong.ants.manager.HttpManager;
import com.yicong.ants.utils.L;
import com.yicong.ants.utils.ToastUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;

/**
 * 负责下载最新apk文件的Service
 */
public class DownloadService extends Service {

    private OnProgressListener listener;
    private boolean isStart;

    public void setListener(OnProgressListener listener) {
        this.listener = listener;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isStart && null != intent) {
            isStart = true;
            download(intent);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void download(Intent intent) {
        String fileUrl = intent.getStringExtra("fileUrl");
        String filePath = intent.getStringExtra("filePath");
        String fileName = intent.getStringExtra("fileName");
        L.e("onStartCommand--->", fileUrl + "   " + filePath + "  " + fileName);
        HttpManager.getHttp(fileUrl, null, new FileCallBack(filePath, fileName) {
            @Override
            public void onError(Call call, Exception e, int id) {
                L.e("Exception------->", e.getMessage());
                ToastUtils.showShort(getApplicationContext(), "安装包下载出错，请检查网络");
            }

            @Override
            public void inProgress(float progress, long total, int id) {
                super.inProgress(progress, total, id);
                if (null != listener) {
                    int pro = (int) (progress * 100);
                    L.e("inProgress", String.valueOf(pro));
                    listener.updateProgress(pro);
                }
            }

            @Override
            public void onResponse(File response, int id) {
                //会根据用户的数据类型打开android系统相应的Activity。
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    intent.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive");
                } else {//Android7.0之后获取uri要用contentProvider
                    intent.setDataAndType(Uri.parse("file://" + response.toString()), "application/vnd.android.package-archive");
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                //开始安装
                startActivity(intent);
                //关闭旧版本的应用程序的进程
                // android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
    }

    public interface OnProgressListener {
        void updateProgress(int progress);
    }

    public class MsgBinder extends Binder {
        /**
         * 获取当前Service的实例
         *
         * @return
         */
        public DownloadService getService() {
            return DownloadService.this;
        }
    }
}
